package com.newer.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid 连接数据库的工具类(推荐)
 */
public class DruidUtil {
    // 数据源(数据库连接池)
    private static DataSource ds = null;

    static {

        try {
            Properties prop = new Properties();
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
            prop.load(is);

            // 通过工厂类创建数据源
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static void closeAll(ResultSet rs,Statement st,Connection conn) {
        try{
            if(rs!=null)rs.close();
            if(st!=null)st.close();
            if(conn!=null)conn.close();

        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SQLException {
        System.out.println(getConnection());
    }
}
